package ru.ifmo.tanya.service.mock;

import ru.ifmo.tanya.core.calls.CallManager;
import ru.ifmo.tanya.core.users.User;
import ru.ifmo.tanya.core.users.UserState;
import ru.ifmo.tanya.keepers.UserStateKeeper;
import ru.ifmo.tanya.service.HttpService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class EndCallService implements HttpService {

    private final CallManager callManager = new CallManager();
    private final UserStateKeeper userStateKeeper = new UserStateKeeper();

    @Override
    public void invoke(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int id = Integer.parseInt(request.getParameter("call-id"));
        String actionMaker = request.getParameter("who");
        callManager.callEnded(id, actionMaker);
        User answerer = callManager.getCallAnswerer(id);
        if (answerer != null) {
            userStateKeeper.updateState(answerer, UserState.AVAILABLE);
        }
        PrintWriter out = new PrintWriter(response.getOutputStream());
        out.println("OK");
        out.close();
    }
}
